from com.arcfox.manager.redis_task_manager import RedisTaskManager
from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.redis_key_manager import HAND_UNIVERSITY_SCHOOL_LIST_KEY


class HandSchoolListProcessor(BaseProcessor):
    def __init__(self):
        self.task_manager = RedisTaskManager(HAND_UNIVERSITY_SCHOOL_LIST_KEY)

    async def parse_and_add_task(self, result_json):
        result_data = result_json['data']
        tasks = []
        for item in result_data['item']:
            university_name = item['name']
            school_id = item['school_id']
            tasks.append({
                "uid": self.generate_school_uid(university_name),
                "name": university_name,
                "school_id": school_id,
            })
        await self.task_manager.add_tasks(tasks)

    async def parse_and_save_school_address(self, task, result_json):
        '''
        更新院校地址和占地面积
        :return:
        '''
        result_data = result_json['data']
        university_area = result_data['area']
        university_address = result_data['address']
        mapping = db.MysqlMapping("tb_university_info")
        await mapping.update({"university_area": university_area, "university_address": university_address},
                             {"university_uid": task['uid']})

    async def parse_and_save_school_summary(self, task, result_json):
        '''
        更新院校简介
        :return:
        '''
        result_data = result_json['data']
        content = result_data['content']
        update_time = result_data['update_time']
        data = {
            "university_uid": task['uid'],
            "university_name": task['name'],
            "university_summary": content,
            "update_time": update_time
        }
        mapping = db.MysqlMapping("tb_university_summary")
        old_data = await mapping.query({"university_uid": task['uid']}, ['id'])
        if old_data:
            await mapping.update({"university_summary": content, "update_time": update_time},
                                 {"university_uid": task['uid']})
        else:
            await mapping.insert(data)
